<template>
  <el-main>
    <header>
      <el-row :gutter="20">
        <el-col :span="2">
          <div class="">
            <span>设备编号:</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="">
            <el-input v-model="innerCode" placeholder="请输入"></el-input>
          </div>
        </el-col>
        <el-col :span="2">
          <div class="">
            <el-button @click="searchFn" type="primary" icon="el-icon-search">查询</el-button>
          </div>
        </el-col>
        <el-col :span="14">
          <div class=""></div>
        </el-col>
      </el-row>
    </header>
    <main>
      <div class="top">
        <el-button class="add" @click="addFn" icon="el-icon-circle-plus-outline">新建</el-button>
        <el-button class="batch" @click="batch">批量管理</el-button>
        <el-dialog class="dialogAdd" title="新增设备" :visible.sync="addEquipment" width="35%" :modal-append-to-body="false">
          <div>
            <div class="header">
              <div>设备编号：</div>
              <div>系统自动生成</div>
            </div>
            <el-form ref="fromAdd" label-position="left" :model="fromAdd" :rules="rulesAdd" @close="closeFn">
              <el-form-item prop="vmType" label="选择型号：">
                <el-select v-model="fromAdd.vmType" placeholder="请选择">
                  <el-option v-for="item in optionsType" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="nodeId" label="选择点位：">
                <el-select v-model="fromAdd.nodeId" placeholder="请选择">
                  <el-option v-for="item in optionsNode" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="closeFn">取 消</el-button>
            <el-button type="primary" @click="add">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <div class="middle">
        <template>
          <el-table ref="table" :data="tableData" style="width: 100%">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="no" label="序号"> </el-table-column>
            <el-table-column prop="innerCode" label="设备编号"> </el-table-column>
            <el-table-column prop="typeName" label="设备型号"> </el-table-column>
            <el-table-column prop="nodeName" label="详细地址"> </el-table-column>
            <el-table-column prop="ownerName" label="合作商"> </el-table-column>
            <el-table-column prop="vmStatus" label="设备状态"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="aisle(scope.row)">货道</el-button>
                <el-button type="text" @click="policy(scope.row)">策略</el-button>
                <el-button type="text" @click="change(scope.row)">修改</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <el-dialog class="dialogChange" title="修改设备" :visible.sync="dialogChange" width="35%" :modal-append-to-body="false">
          <div>
            <div class="leftChange">机器编号:</div>
            <div class="rightChange">{{ formChange.innerCode }}</div>
          </div>
          <div>
            <div class="leftChange">供货时间:</div>
            <div class="rightChange">{{ formChange.lastSupplyTime }}</div>
          </div>
          <div v-if="formChange.type">
            <div class="leftChange">设备类型:</div>
            <div class="rightChange">{{ formChange.type.name }}</div>
          </div>
          <div v-if="formChange.type">
            <div class="leftChange">设备容量:</div>
            <div class="rightChange">{{ formChange.type.channelMaxCapacity }}</div>
          </div>
          <div>
            <div class="leftChange">设备点位:</div>
            <div class="rightChange">
              <el-select v-model="Node" placeholder="请选择">
                <el-option v-for="item in NodeSearch" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </div>
          </div>
          <div>
            <div class="leftChange">合作商:</div>
            <div class="rightChange">{{ formChange.ownerName }}</div>
          </div>
          <div v-if="formChange.node">
            <div class="leftChange">所属地区:</div>
            <div class="rightChange">{{ formChange.node.region.name }}</div>
          </div>
          <div v-if="formChange.node">
            <div class="leftChange">设备地址:</div>
            <div class="rightChange">{{ formChange.node.name }}</div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogChange = false">取 消</el-button>
            <el-button type="primary" @click="changeNode">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog class="dialogPolicy" title="策略管理" :visible.sync="policyEquipment" width="35%" :modal-append-to-body="false">
          <span>选择策略：</span>
          <el-select v-model="policyId" placeholder="请选择" value="">
            <el-option v-for="item in policyList" :key="item.policyId" :label="item.policyName" :value="item.policyId"> </el-option>
          </el-select>
          <span slot="footer" class="dialog-footer">
            <el-button @click="policyEquipment = false">取 消</el-button>
            <el-button type="primary" @click="addPolicy">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog class="dialogPolicy policytView" title="策略管理" :visible.sync="policytView" width="35%" :modal-append-to-body="false">
          <div>
            <span>机器编号：</span>
            <span>{{ policyCurrent.innerCode }}</span>
          </div>
          <div>
            <span>策略名称：</span>
            <span>{{ policyCurrent.policyName }}</span>
          </div>
          <div>
            <span>策略方案：</span>
            <span>{{ policyCurrent.discount }}%</span>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelPolicy">取消策略</el-button>
          </span>
        </el-dialog>
        <el-dialog class="dialogAisle" title="货道设置" :visible.sync="dialogAisle" width="45%" :modal-append-to-body="false">
          <el-dialog class="aisleSort" width="40%" title="智能排序" :visible.sync="aisleSort" append-to-body>
            <p>该区域属于{{ business }}商圈适合销售一下商品：</p>
            <el-row :gutter="10">
              <el-col v-for="item in businessTop" :key="item.skuId" :span="4">
                <div>
                  <img :src="item.image" alt="" />
                  <p>{{ item.skuName }}</p>
                </div>
              </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="adopt">采纳建议</el-button>
            </span>
          </el-dialog>
          <el-dialog class="aisleSort" width="40%" title="选择商品" :visible.sync="addGoods" append-to-body>
            <div style="display: flex; margin-bottom: 20px" class="search">
              <span style="width: 100px; line-height: 40px">商品名称：</span>
              <el-input class="searchInput" v-model="goodsName" placeholder="请输入内容"></el-input>
              <el-button type="primary" icon="el-icon-search" @click="searchGoods">查询</el-button>
            </div>
            <el-scrollbar style="height: 350px">
              <el-row :gutter="10">
                <el-col style="position: relative" v-for="(item, index) in skuSearch.currentPageRecords" :key="index" :span="4">
                  <div @click="tick(index)">
                    <img
                      class="active"
                      style="position: absolute; top: -10px; left: -15px; width: 36px; height: 36px"
                      :src="
                        item.tickImg
                          ? item.tickImg
                          : 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.99ppt.com%2Fpic%2F7d357df5-a42c-4cef-aa31-9ff335b13402.png&refer=http%3A%2F%2Fimg.99ppt.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1672367481&t=8e6ecbbe61c47207813ac5db7c90a564'
                      "
                      alt=""
                    />
                    <img :src="item.skuImage" alt="" />
                    <p style="height: 40px">{{ item.skuName }}</p>
                  </div>
                </el-col>
              </el-row>
            </el-scrollbar>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="addGood" :disabled="!tfTick">确认</el-button>
            </span>
          </el-dialog>
          <div>
            <div class="top">
              <div>
                <span>货道行数：</span>
                <span>{{ vmTypet.vmRow }}</span>
              </div>
              <div>
                <span>货道列数：</span>
                <span>{{ vmTypet.vmCol }}</span>
              </div>
              <div>
                <span>货道容量（个）：</span>
                <span>{{ vmTypet.channelMaxCapacity }}</span>
              </div>
              <el-button type="primary" @click="sort">智能排货</el-button>
            </div>
            <el-scrollbar style="height: 350px">
              <el-row :gutter="10">
                <el-col v-for="item in channelList" :key="item.channelId" :span="4">
                  <div class="bottom">
                    <div class="goods">
                      <span>&nbsp;{{ item.channelCode }}</span>
                      <img
                        :src="
                          item.sku
                            ? item.sku.skuImage || item.sku.image
                            : ''
                        "
                        alt=""
                      />
                      <p>{{ item.sku ? item.sku.skuName : '暂无商品' }}</p>
                    </div>
                    <div class="name">
                      <el-button type="text" @click="addGoodsFn(item.channelId)">添加</el-button>
                      <el-button type="text" @click="delGoods(item.channelId)">删除</el-button>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-scrollbar>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submit">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <div class="bottom">
        <span>共{{ search.totalCount }}条记录 第 {{ search.pageIndex }}/{{ search.totalPage }} 页</span>
        <el-button @click="onPage" :disabled="getSearchObj.pageIndex === 1">上一页</el-button>
        <el-button @click="bownPage" :disabled="getSearchObj.pageIndex == search.totalPage">下一页</el-button>
      </div>
    </main>
  </el-main>
</template>

<script>
import { getSearch, getNodeSearch, getVmService, getTypeSearch, addVmService, getPolicyList, getVmPolicy, putCancelPolicy, putApplyPolicy, getVmTypet, getChannelList, getBusinessType, getBusinessTop, getSkuSearch, getSearchGoods, putChannelConfig } from '@/api/equipment'
export default {
  data () {
    return {
      getSearchObj: {
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      search: {},
      innerCode: '',
      dialogChange: false,
      optionsChange: [],
      NodeSearch: [],
      Node: '',
      formChange: {},
      addEquipment: false,
      fromAdd: {
        vmType: '',
        nodeId: ''
      },
      optionsType: [],
      optionsNode: [],
      rulesAdd: {
        vmType: [{ required: true, message: '请选择' }],
        nodeId: [{ required: true, message: '请选择' }]
      },
      policyEquipment: false,
      policyList: [],
      policytView: false,
      policyCurrent: {},
      policyId: '',
      innerCodeCurrent: '',
      selection: [],
      dialogAisle: false,
      vmTypet: {},
      channelList: [],
      aisleSort: false,
      aisledata: {},
      business: '',
      businessTop: [],
      addGoods: false,
      goodsName: '',
      skuSearch: [],
      currentTick: {},
      currentChannelId: ''
    }
  },
  computed: {
    tfTick () {
      const tfTick = []
      this.skuSearch.currentPageRecords?.forEach((item) => {
        if (item.tickImg) {
          tfTick.push(item.tickImg)
        }
      })
      return tfTick.length
    }
  },
  created () {
    this.getSearch(this.getSearchObj)
  },
  methods: {
    async getSearch (getSearchObj) {
      const search = await getSearch(getSearchObj)
      this.search = search
      console.log(this.search)
      search.currentPageRecords.forEach((item, index) => {
        this.tableData.push({
          no: search.pageIndex * 10 - 9 + index,
          innerCode: item.innerCode,
          typeName: item.type.name,
          nodeName: item.node.name,
          ownerName: item.ownerName,
          vmStatus: item.vmStatus === 0 ? '未投放' : item.vmStatus === 1 ? '运营' : '撤机',
          typeId: item.type.typeId
        })
      })
    },
    async onPage () {
      this.getSearchObj.pageIndex--
      this.tableData = []
      this.getSearch(this.getSearchObj)
    },
    async bownPage () {
      this.getSearchObj.pageIndex++
      this.tableData = []
      this.getSearch(this.getSearchObj)
    },
    async searchFn () {
      const searchFnObj = this.getSearchObj
      this.$set(searchFnObj, 'innerCode', this.innerCode)
      this.tableData = []
      this.getSearch(searchFnObj)
    },
    async change (row) {
      this.dialogChange = true
      const { currentPageRecords } = await getNodeSearch()
      this.NodeSearch = currentPageRecords
      this.formChange = this.search.currentPageRecords.filter((item) => item.innerCode === row.innerCode)[0]
      console.log(this.formChange)
      console.log(this.NodeSearch)
      this.formChange.lastSupplyTime = this.formChange.lastSupplyTime.replace(/-/g, '.').replace(/T/g, ' ')
      this.Node = this.formChange.node.name
    },
    async changeNode () {
      try {
        await getVmService({ id: this.formChange.id, nodeId: this.Node })
        this.$message.success('修改成功')
      } catch (error) {
        console.log(error)
      }
      this.dialogChange = false
    },
    async addFn () {
      this.fromAdd = {
        vmType: '',
        nodeId: ''
      }
      this.optionsType = []
      this.optionsNode = []
      this.addEquipment = true
      const optionsType = await getTypeSearch({ pageIndex: 1, pageSize: 100000 })
      optionsType.currentPageRecords.forEach((item) => {
        this.optionsType.push({ label: item.name, value: item.typeId })
      })
      const optionsNode = await getNodeSearch({ pageIndex: 1, pageSize: 100000 })
      optionsNode.currentPageRecords.forEach((item) => {
        this.optionsNode.push({ label: item.name, value: item.id })
      })
    },
    closeFn () {
      this.addEquipment = false
      this.$refs.fromAdd.resetFields()
    },
    async add () {
      try {
        await this.$refs.fromAdd.validate()
        await addVmService({ ...this.fromAdd, createUserId: 1 })
        this.addEquipment = false
        this.getSearch(this.getSearchObj)
      } catch (error) {
        console.log(error)
      }
    },
    async policy (row) {
      console.log(row)
      this.policyId = ''
      this.innerCodeCurrent = row.innerCode
      const policy = await getVmPolicy(row.innerCode)
      this.policyCurrent = policy
      if (policy) {
        this.policytView = true
      } else {
        const policyList = await getPolicyList()
        this.policyList = policyList
        this.policyEquipment = true
      }
    },
    async cancelPolicy () {
      await putCancelPolicy(this.policyCurrent.innerCode, this.policyCurrent.policyId)
      this.policytView = false
    },
    async putApplyPolicy (innerCodeCurrent) {
      await putApplyPolicy({ innerCodeList: innerCodeCurrent, policyId: this.policyId })
    },
    async addPolicy () {
      if (this.$refs.table.selection.length === 0) {
        this.putApplyPolicy([this.innerCodeCurrent])
      } else {
        this.$refs.table.selection.forEach((item) => {
          this.selection.push(item.innerCode)
        })
        this.putApplyPolicy(this.selection)
        this.selection = []
      }
      this.policyEquipment = false
    },
    async batch () {
      console.log(this.$refs.table.selection)
      if (this.$refs.table.selection.length === 0) {
        this.$message({
          message: '请勾选售货机',
          type: 'warning'
        })
      } else {
        const policyList = await getPolicyList()
        this.policyList = policyList
        this.policyEquipment = true
      }
    },
    async aisle (row) {
      this.aisledata = row
      this.vmTypet = await getVmTypet(row.typeId)
      const channelList = await getChannelList(row.innerCode)
      this.channelList = channelList
      console.log(this.channelList)
      this.dialogAisle = true
    },
    delGoods (id) {
      this.channelList.forEach((item) => {
        if (item.channelId === id) {
          item.sku = null
        }
      })
    },
    async sort () {
      this.aisleSort = true
      this.business = await getBusinessType(this.aisledata.typeId)
      this.businessTop = await getBusinessTop(this.aisledata.typeId)
      console.log(this.businessTop)
    },
    adopt () {
      this.businessTop.forEach((item, index) => {
        this.channelList[index].sku = item
      })
      this.aisleSort = false
    },
    async addGoodsFn (id) {
      this.currentChannelId = id
      this.goodsName = ''
      this.addGoods = true
      this.skuSearch = await getSkuSearch()
      console.log(this.skuSearch.currentPageRecords)
    },
    async tick (i) {
      this.skuSearch = await getSkuSearch()
      this.$set(
        this.skuSearch.currentPageRecords[i],
        'tickImg',
        ''
      )
      console.log(this.skuSearch)
    },
    async searchGoods () {
      if (this.goodsName) {
        this.skuSearch = await getSearchGoods(this.goodsName)
      } else {
        this.skuSearch = await getSkuSearch()
      }
    },
    addGood () {
      this.skuSearch.currentPageRecords?.forEach((item) => {
        if (item.tickImg) {
          this.currentTick = item
        }
      })
      this.channelList.forEach((item) => {
        if (item.channelId === this.currentChannelId) {
          item.sku = this.currentTick
        }
      })
      this.addGoods = false
    },
    async submit () {
      const innerCode = this.aisledata.innerCode
      const channelList = []
      this.channelList.forEach(item => {
        channelList.push({ channelCode: item.channelCode, skuId: item.skuId })
      })
      await putChannelConfig({ innerCode, channelList })
      this.dialogAisle = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-main {
  background-color: RGB(248, 250, 253);
  width: 89vw;
  height: 100%;
  header {
    background-color: #fff;
    height: 64px;
    margin-bottom: 20px;
    span {
      line-height: 64px;
      margin-left: 20px;
    }
    .el-input {
      margin-top: 12px;
    }
    button {
      background-color: RGB(95, 132, 255);
      margin-top: 10px;
    }
  }
  main {
    background-color: #fff;
    // height: 634px;
    padding: 20px 15px 19px 17px;
    .top {
      margin-bottom: 20px;
      button {
        border: none;
      }
      .add {
        color: #fff;
        background: linear-gradient(135deg, #ff9743, #ff5e20);
      }
      .batch {
        background-color: #fbf4f0;
      }
    }
    .middle {
      /deep/ td {
        border-bottom: 0px solid #ebeef5;
      }
      /deep/ th {
        background-color: RGB(243, 246, 251);
        font-weight: 400;
        color: #333;
      }
    }
    .bottom {
      padding: 32px 16px;
      display: flex;
      span {
        flex: 1;
        font-size: 16px;
        color: #dbdfe5;
      }
      button {
        border: none;
        background-color: #d5ddf8;
      }
    }
  }
}
/deep/ .dialogChange {
  .el-dialog {
    border-radius: 10px;
  }
  .el-dialog__header {
    font-weight: 700;
  }
  .el-dialog__body {
    padding: 20px 60px;
    > div {
      display: flex;
      height: 36px;
      line-height: 36px;
      margin-bottom: 20px;
      .leftChange {
        width: 100px;
      }
      .rightChange {
        flex: 1;
        .el-select {
          width: 100%;
        }
      }
    }
  }
  .el-dialog__footer {
    button:nth-child(1) {
      background-color: #fbf4f0 !important;
      border: none;
      color: #655b56 !important;
    }
    button:nth-child(2) {
      background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
      border: none;
    }
    text-align: center;
  }
}
/deep/ .dialogAdd {
  .el-dialog {
    border-radius: 10px;
  }
  .el-dialog__header {
    font-weight: 700;
  }
  .el-dialog__body {
    padding: 20px 60px;
    .header {
      display: flex;
      div {
        margin-right: 12px;
        margin-bottom: 22px;
      }
    }
    .el-select {
      width: 80%;
    }
    .el-form-item__label {
      text-align: left;
    }
  }
  .el-dialog__footer {
    button:nth-child(1) {
      background-color: #fbf4f0 !important;
      border: none;
      color: #655b56 !important;
    }
    button:nth-child(2) {
      background: linear-gradient(135deg, #ff9743, #ff5e20);
      border: none;
    }
    text-align: center;
  }
}
/deep/ .dialogPolicy {
  .el-dialog {
    border-radius: 10px;
  }
  .el-dialog__header {
    font-weight: 700;
  }
  .el-dialog__body {
    padding: 20px 60px;
    .el-select {
      width: 80%;
    }
  }
  .el-dialog__footer {
    button:nth-child(1) {
      background-color: #fbf4f0 !important;
      border: none;
      color: #655b56 !important;
    }
    button:nth-child(2) {
      background: linear-gradient(135deg, #ff9743, #ff5e20);
      border: none;
    }
    text-align: center !important;
  }
}
.policytView {
  .el-dialog__body {
    div {
      margin-bottom: 20px;
    }
  }
}
/deep/ .dialogAisle {
  .el-dialog {
    border-radius: 10px;
  }
  .el-dialog__header {
    font-weight: 700;
  }
  .el-dialog__body {
    padding: 20px 60px;
    .el-select {
      width: 80%;
    }
    .top {
      display: flex;
      line-height: 56px;
      width: 100%;
      height: 56px;
      margin-bottom: 16px;
      background: #f3f6fb;
      div {
        margin: 0 30px;
      }
      button {
        margin-left: auto;
        margin-top: 10px;
        margin-right: 25px;
        align-items: center;
        min-width: 80px;
        height: 36px;
        padding: 0;
        background-color: #5f84ff;
        border: none;
      }
    }
    .bottom {
      height: 180px;
      padding: 0;
      flex-direction: column;
      .goods {
        position: relative;
        width: 100%;
        height: 140px;
        background: #f3f6fb;
        img {
          width: 84px;
          height: 78px;
          margin-top: 15px;
          margin-left: 15px;
        }
        span {
          display: inline;
          position: absolute;
          top: 10px;
          left: 0;
          width: 30px;
          height: 23px;
          line-height: 23px;
          background: #829bed;
          border-radius: 0 10px 10px 0;
          font-size: 12px;
          color: #fff;
        }
        p {
          text-align: center;
          line-height: 30px;
        }
      }
      .name {
        width: 100%;
        height: 40px;
        background-color: #fff;
        text-align: center;
        button {
          background-color: #fff;
        }
        button:nth-child(1) {
          border: none;
          color: #5f84ff !important;
        }
        button:nth-child(2) {
          color: #ff5a5a;
          border: none;
        }
      }
    }
  }
  .el-dialog__footer {
    button {
      background: linear-gradient(135deg, #ff9743, #ff5e20);
      border: none;
    }
    text-align: center !important;
  }
}
</style>
